package cn.sypt.yuhao.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.servlet.BaseServlet;
import cn.sypt.yuhao.dao.AcategoryDao;
import cn.sypt.yuhao.dao.VideoDao;
import cn.sypt.yuhao.domain.Acategory;
import cn.sypt.yuhao.domain.Video;
import cn.sypt.yuhao.pager.PageBean;

public class AcategoryServlet extends BaseServlet {
	private AcategoryDao sd=new AcategoryDao();
	private VideoDao vd=new VideoDao();
	public void findAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("ajax");
		String name="张三";
		response.getWriter().print(name);
	}
	public String findByfid(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String fid=request.getParameter("fid");
		List<Acategory> scategoryList=sd.findByfid(fid);
	//	System.out.println(scategoryList);
		request.getSession().setAttribute("list1", scategoryList);
		//response.getWriter().print(scategoryList);
		
		int pc=getPc(request);
		String url=getUrl(request);
		//String bid=request.getParameter("fid");
		PageBean<Video> pb= (PageBean<Video>) vd.findByfid(pc, fid);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		return "f:/ui/products.jsp";
	}
	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		if(param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch(RuntimeException e) {}
		}
		return pc;
	}
	
	/**
	 * 截取url，页面中的分页导航中需要使用它做为超链接的目标！
	 * @param req
	 * @return
	 */
	
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		/*
		 * 如果url中存在pc参数，截取掉，如果不存在那就不用截取。
		 */
		int index = url.lastIndexOf("&pc=");
		if(index != -1) {
			url = url.substring(0, index);
		}
		return url;
	}
}
